﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Collections;
using System.Data;
using System.Security.Cryptography;
using System.Text;

namespace ManagerVerification
{
    /// <summary>
    /// Сводное описание для KrishaService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // Чтобы разрешить вызывать веб-службу из скрипта с помощью ASP.NET AJAX, раскомментируйте следующую строку. 
    // [System.Web.Script.Services.ScriptService]
    public class KrishaService : System.Web.Services.WebService
    {

        public KrishaService()
        {
        }

        private Hashtable UserSessions
        {
            get
            {
                if (HttpContext.Current.Application["UserSessions"] == null)
                {
                    HttpContext.Current.Application.Add("UserSessions", new Hashtable());

                    return null;
                }
                else
                {
                    return ((Hashtable)HttpContext.Current.Application["UserSessions"]);
                }
            }
            set
            {
                HttpContext.Current.Application.Add("UserSessions", (Hashtable)value);
            }
        }
        private Hashtable ApplicationIDList
        {
            get
            {
                if (HttpContext.Current.Application["ApplicationIDList"] == null)
                {
                    HttpContext.Current.Application.Add("ApplicationIDList", new Hashtable());

                    return null;
                }
                else
                {
                    return ((Hashtable)HttpContext.Current.Application["ApplicationIDList"]);
                }
            }
            set
            {
                HttpContext.Current.Application.Add("ApplicationIDList", (Hashtable)value);
            }
        }

        private Guid? GET_UserID(string hash)
        {
            if (UserSessions == null)
            {
                UserSessions = new Hashtable();
            }

            if (UserSessions.ContainsKey(hash))
            {
                return Guid.Parse(UserSessions[hash].ToString());
            }

            return null;
        }
        private string GET_ApplicationID(Guid managerID)
        {
            if (ApplicationIDList == null)
            {
                ApplicationIDList = new Hashtable();
            }

            if (ApplicationIDList.ContainsKey(managerID))
            {
                return ApplicationIDList[managerID].ToString();
            }

            return null;
        }
        private void SET_UserID(string sessionID, string userID)
        {
            if (UserSessions == null)
            {
                UserSessions = new Hashtable();
            }

            UserSessions.Add(sessionID, userID);
        }
        private void SET_ApplicationID(Guid? managerID, string applicationID)
        {
            if (ApplicationIDList == null)
            {
                ApplicationIDList = new Hashtable();
            }

            if (managerID == null)
            {
                return;
            }

            ApplicationIDList.Add(managerID, applicationID);
        }
        private string Contains_UserID(string userID)
        {
            if (UserSessions == null)
            {
                UserSessions = new Hashtable();
            }

            if (UserSessions.ContainsValue(userID))
            {
                foreach (object key in UserSessions.Keys)
                {
                    if (UserSessions[key.ToString()].ToString() == userID)
                    {
                        return key.ToString();
                    }
                }
            }
            return null;
        }
        #region MobileClient

        [WebMethod]
        public string GET_ClientAutentification(string login, string password)
        {
            try
            {
                SHA256 ShaM = new SHA256Managed();
                byte[] encPassword = ShaM.ComputeHash(Encoding.ASCII.GetBytes(password));

                using (var ta = WebUser.GET_ClientVerification)
                using (var table = ta.GetData(login, encPassword))
                {
                    if (table.Rows.Count > 0)
                    {
                        if ((bool)(table.Rows[0]["IsSuccessful"]) == false)
                            return null; // не совпал пароль с логином
                        else
                        {
                            string SessionID = Contains_UserID(table.Rows[0]["ClientID"].ToString());
                            if (string.IsNullOrEmpty(SessionID))
                            {
                                SessionID = Guid.NewGuid().ToString();
                                SET_UserID(SessionID, table.Rows[0]["ClientID"].ToString());
                            }
                            return SessionID; //успех операции
                        }
                    }
                    else return null; //не найден логин в таблице
                }
            }
            catch (Exception exc)
            {
                return null;
            }
        }

        [WebMethod]
        public string GET_WareInfo(string SHCode, string hash)
        {
            try
            {
                if (!string.IsNullOrEmpty(SHCode))
                {
                    using (var ta = WebWare.GET_WareBySHCode)
                    using (var table = ta.GetData(SHCode))
                    {
                        if (table.Rows.Count > 0)
                        {
                            Hashtable result = new Hashtable();
                            foreach (DataRow row in table)
                            {
                                Hashtable list = new Hashtable();

                                for (int i = 0; i < table.Columns.Count; i++)
                                {
                                    list.Add(table.Columns[i].ToString(), (row[i] == null ? string.Empty : row[i].ToString()));
                                }

                                Guid? clientID = GET_UserID(hash);
                                Guid wareID = Guid.Parse(row["WaresID"].ToString());
                                string IsFavorite = "false";
                                string IsMarked = "false";

                                if (clientID != null)
                                {
                                    //Add IsFavorite
                                    using (var ta2 = WebWare.GET_IsFavoriteWare)
                                    using (var table2 = ta2.GetData(wareID, clientID))
                                    {
                                        if (table2.Rows.Count > 0)
                                        {
                                            if (table2.Rows[0]["IsFavorite"].ToString() == "1")
                                            {
                                                IsFavorite = "true";
                                            }
                                        }
                                    }
                                    //Add IsMarked
                                    using (var ta2 = WebWare.GET_IsMarkedWare)
                                    using (var table2 = ta2.GetData(wareID, clientID))
                                    {
                                        if (table2.Rows.Count > 0)
                                        {
                                            if (table2.Rows[0]["IsMarked"].ToString() == "1")
                                            {
                                                IsMarked = "true";
                                            }
                                        }
                                    }
                                }
                                list.Add("IsFavorite", IsFavorite);
                                list.Add("IsMarked", IsMarked);

                                result.Add(row["Shop"].ToString(), list);
                            }

                            System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                            string json = jsSerializer.Serialize(result);

                            return json;
                        }
                        else
                        {
                            return null;
                        }
                    }
                }
                return null;
            }
            catch (Exception exc)
            {
                return null;
            }
        }

        [WebMethod]
        public bool MarkedWareForChanges(string wareID, string shop, string hash)
        {
            try
            {
                Guid WareID;
                if (!Guid.TryParse(wareID, out WareID))
                {
                    return false;
                }

                Guid? clientID = GET_UserID(hash);
                if (clientID != null)
                {
                    using (var ta = WebWare.ADD_WareForChanges)
                    using (var table = ta.GetData(WareID, shop, clientID))
                    {
                        return true;
                    }
                }

                return false;
            }
            catch (Exception exc)
            {
                return false;
            }
        }

        [WebMethod]
        public bool ADD_WareToFavorites(string wareID, string hash)
        {
            try
            {
                Guid WareID;
                if (!Guid.TryParse(wareID, out WareID))
                {
                    return false;
                }

                Guid? clientID = GET_UserID(hash);
                if (clientID != null)
                {
                    using (var ta = WebWare.ADD_FavoriteWare)
                    using (var table = ta.GetData(WareID, clientID))
                    {
                        return true;
                    }
                }

                return false;
            }
            catch (Exception exc)
            {
                return false;
            }
        }

        [WebMethod]
        public string GET_WareStaff(string wareID)
        {
            try
            {
                Guid WareID;
                if (!Guid.TryParse(wareID, out WareID))
                {
                    return null;
                }

                using (var ta = WebWare.GET_Ware)
                using (var table = ta.GetData(WareID))
                {
                    if (table.Rows.Count > 0)
                    {
                        string StaffListGuid = "";
                        if (table.Rows[0]["StaffListGuid"] != null)
                        {
                            StaffListGuid = table.Rows[0]["StaffListGuid"].ToString();

                            using (var ta2 = WebWare.GET_StaffList)
                            using (var table2 = ta2.GetData(StaffListGuid))
                            {
                                Hashtable result = new Hashtable();
                                foreach (DataRow row in table2)
                                {
                                    Hashtable list = new Hashtable();

                                    for (int i = 0; i < table2.Columns.Count; i++)
                                    {
                                        list.Add(table2.Columns[i].ToString(), (row[i] == null ? string.Empty : row[i].ToString()));
                                    }

                                    result.Add(row["Name"].ToString(), list);
                                }

                                System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                                string json = jsSerializer.Serialize(result);

                                return json;
                            }
                        }
                    }
                }

                return null;
            }
            catch (Exception exc)
            {
                return null;
            }
        }

        [WebMethod]
        public string GET_ClientCheckLists(string hash)
        {
            try
            {
                Guid? clientID = GET_UserID(hash);
                if (clientID != null)
                {
                    using (var ta = WebUser.GET_ClientCheckLists)
                    using (var table = ta.GetData(clientID))
                    {
                        if (table.Rows.Count > 0)
                        {
                            Hashtable result = new Hashtable();

                            foreach (DataRow row in table)
                            {
                                Hashtable list = new Hashtable();

                                for (int i = 0; i < table.Columns.Count; i++)
                                {
                                    list.Add(table.Columns[i].ToString(), (row[i] == null ? string.Empty : row[i].ToString()));
                                }

                                result.Add(row["Name"].ToString(), list);
                            }

                            System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                            string json = jsSerializer.Serialize(result);

                            return json;
                        }
                    }
                }

                return null;
            }
            catch (Exception exc)
            {
                return null;
            }
        }

        [WebMethod]
        public string GET_Shops()
        {
            try
            {
                using (var ta = WebWare.GET_Shops)
                using (var table = ta.GetData())
                {
                    if (table.Rows.Count > 0)
                    {
                        Hashtable result = new Hashtable();

                        foreach (DataRow row in table)
                        {
                            Hashtable list = new Hashtable();

                            for (int i = 0; i < table.Columns.Count; i++)
                            {
                                list.Add(table.Columns[i].ToString(), (row[i] == null ? string.Empty : row[i].ToString()));
                            }

                            result.Add(row["Shop"].ToString(), list);
                        }

                        System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                        string json = jsSerializer.Serialize(result);

                        return json;
                    }
                }

                return null;
            }
            catch (Exception exc)
            {
                return null;
            }
        }

        [WebMethod]
        public string GET_CheckList(string checkListID)
        {
            try
            {
                Guid CheckListID;
                if (!Guid.TryParse(checkListID, out CheckListID))
                {
                    return null;
                }

                using (var ta = WebUser.GET_CheckList)
                using (var table = ta.GetData(CheckListID))
                {
                    if (table.Rows.Count > 0)
                    {
                        Hashtable result = new Hashtable();

                        foreach (DataRow row in table)
                        {
                            Hashtable list = new Hashtable();

                            for (int i = 0; i < table.Columns.Count; i++)
                            {
                                list.Add(table.Columns[i].ToString(), (row[i] == null ? string.Empty : row[i].ToString()));
                            }

                            result.Add(row["Name"].ToString(), list);
                        }

                        System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                        string json = jsSerializer.Serialize(result);

                        return json;
                    }
                }

                return null;
            }
            catch (Exception exc)
            {
                return null;
            }
        }

        #endregion

        #region ComplectMobile

        [WebMethod]
        public string GET_ManagerAutentification(string login, string password)
        {
            try
            {
                SHA256 ShaM = new SHA256Managed();
                byte[] encPassword = ShaM.ComputeHash(Encoding.ASCII.GetBytes(password));

                using (var ta = WebUser.GET_ManagerVerification)
                using (var table = ta.GetData(login, encPassword))
                {
                    if (table.Rows.Count > 0)
                    {
                        if ((bool)(table.Rows[0]["IsSuccessful"]) == false)
                            return null; // не совпал пароль с логином
                        else
                        {
                            string SessionID = Contains_UserID(table.Rows[0]["ManagerID"].ToString());
                            if (string.IsNullOrEmpty(SessionID))
                            {
                                SessionID = Guid.NewGuid().ToString();
                                SET_UserID(SessionID, table.Rows[0]["ManagerID"].ToString());
                            }
                            return SessionID; //успех операции                            
                        }
                    }
                    else return null; //не найден логин в таблице
                }
            }
            catch (Exception exc)
            {
                return null;
            }
        }

        [WebMethod]
        public bool SET_ApplicationID(string hash, string applicationID)
        {
            try
            {
                Guid? ManagerID = GET_UserID(hash);
                if (ManagerID != null)
                {
                    SET_ApplicationID(ManagerID, applicationID);
                    return true;

                }

                return false;
            }
            catch (Exception exc)
            {
                return false;
            }
        }

        [WebMethod]
        public string GET_WareAnalogs(string wareID, string hash)
        {
            try
            {
                Guid WareID = Guid.Parse(wareID);
                Guid? LiveID = null, GroupID = null;
                string Shop = "";

                using (var ta = WebWare.GET_Ware)
                using (var table = ta.GetData(WareID))
                {
                    if (table.Rows.Count > 0)
                    {
                        if (table.Rows[0]["LiveID"] != null)
                        {
                            LiveID = Guid.Parse(table.Rows[0]["LiveID"].ToString());
                        }
                        if (table.Rows[0]["GroupID"] != null)
                        {
                            GroupID = Guid.Parse(table.Rows[0]["GroupID"].ToString());
                        }
                        if (table.Rows[0]["Shop"] != null)
                        {
                            Shop = table.Rows[0]["Shop"].ToString();
                        }
                    }
                }

                using (var ta = WebWare.GET_WareAnalogs)
                using (var table = ta.GetData(LiveID, GroupID, Shop))
                {
                    if (table.Rows.Count > 0)
                    {
                        Hashtable result = new Hashtable();
                        foreach (DataRow row in table)
                        {
                            Hashtable list = new Hashtable();

                            for (int i = 0; i < table.Columns.Count; i++)
                            {
                                list.Add(table.Columns[i].ToString(), (row[i] == null ? string.Empty : row[i].ToString()));
                            }

                            Guid? ManagerID = GET_UserID(hash);
                            string IsMarked = "false";
                            if (ManagerID != null)
                            {
                                //Add IsMarked
                                using (var ta2 = WebWare.GET_IsMarkedWare)
                                using (var table2 = ta2.GetData(WareID, ManagerID))
                                {
                                    if (table2.Rows.Count > 0)
                                    {
                                        if (table2.Rows[0]["IsMarked"].ToString() == "1")
                                        {
                                            IsMarked = "true";
                                        }
                                    }
                                }
                            }
                            list.Add("IsMarked", IsMarked);

                            result.Add(row["WareName"].ToString(), list);
                        }

                        System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                        string json = jsSerializer.Serialize(result);

                        return json;
                    }
                    else
                    {
                        return null;
                    }

                }
                return null;
            }
            catch (Exception exc)
            {
                return null;
            }
        }

        [WebMethod]
        public string GET_WaresForChanges(string shop)
        {
            try
            {
                using (var ta = WebWare.GET_WaresForChanges)
                using (var table = ta.GetData(shop))
                {
                    Hashtable result = new Hashtable();

                    foreach (DataRow ware in table)
                    {
                        using (var ta2 = WebWare.GET_Ware)
                        using (var table2 = ta2.GetData(Guid.Parse(ware["WareID"].ToString())))
                        {
                            if (table2.Rows.Count > 0)
                            {
                                DataRow row = table2.Rows[0];
                                Hashtable list = new Hashtable();

                                for (int i = 0; i < table2.Columns.Count; i++)
                                {
                                    list.Add(table2.Columns[i].ToString(), (row[i] == null ? string.Empty : row[i].ToString()));
                                }

                                result.Add(row["WareName"].ToString(), list);
                            }
                        }
                    }

                    System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                    string json = jsSerializer.Serialize(result);

                    return json;
                }

                return null;
            }
            catch (Exception exc)
            {
                return null;
            }
        }

        [WebMethod]
        public bool ChangeWarePrice(string wareID, string hash, string newPriceMain, string newPriceRed)
        {
            try
            {
                Guid WareID = Guid.Parse(wareID);

                Guid? ManagerID = GET_UserID(hash);
                if (ManagerID != null)
                {
                    decimal? NewPriceMain = null;
                    if (!string.IsNullOrEmpty(newPriceMain))
                    {
                        NewPriceMain = decimal.Parse(newPriceMain);
                    }
                    decimal? NewPriceRed = null;
                    if (!string.IsNullOrEmpty(newPriceRed))
                    {
                        NewPriceRed = decimal.Parse(newPriceRed);
                    }
                    using (var ta = WebWare.SET_WarePrice)
                    using (var table = ta.GetData(WareID, NewPriceMain, NewPriceRed))
                    {
                    }

                    using (var ta = WebWare.REMOVE_WaresForChanges)
                    using (var table = ta.GetData(WareID))
                    {
                    }

                    using (var ta = WebWare.ADD_WareAction)
                    using (var table = ta.GetData(WareID, ManagerID, "ChangePrice"))
                    {
                    }

                    return true;
                }

                return false;
            }
            catch (Exception exc)
            {
                return false;
            }
        }

        #endregion
    }
}
